package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserService {
    @Override
    public ResponseResult userLogin(AdUserDTO dto) {
        //1.1  入参参数校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.1  查找数据库中是否有次用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        if (9 != user.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //2.2  密码校验
        String dbPwd = dto.getPassword();
        String salt = user.getSalt();
        String newPwd = DigestUtils.md5DigestAsHex((dbPwd + salt).getBytes());
        if (!newPwd.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //2.3  更新登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //3.1  获取token
        String token = AppJwtUtil.getToken(user.getId().longValue());
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user, adUserVO);
        Map map = new HashMap();
        map.put("token",token);
        map.put("user",adUserVO);


        return ResponseResult.okResult(map);
    }
}
